package service

import (
	"context"
	"errors"
	"fmt"
	"patient-srv/basic/config"
	patient "patient-srv/basic/proto"
	"patient-srv/handler/model"
	"time"

	"gorm.io/gorm"
)

// CreateConsultation 创建问诊
func (s *PatientServiceServer) CreateConsultation(ctx context.Context, req *patient.CreateConsultationRequest) (*patient.CreateConsultationResponse, error) {
	// 1. 验证患者信息
	var patientInfo model.Patient
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.PatientId, req.UserId).First(&patientInfo).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.CreateConsultationResponse{Message: "患者信息不存在"}, nil
		}
		return nil, err
	}

	// 2. TODO: 调用 doctor-srv 验证医生信息，获取问诊费用
	fee := 0.0
	switch req.ConsultationType {
	case 1: // 图文问诊
		fee = 30.0
	case 2: // 电话问诊
		fee = 50.0
	case 3: // 视频问诊
		fee = 80.0
	}

	// 3. 创建问诊记录
	consultation := &model.Consultation{
		UserID:             req.UserId,
		DoctorID:           req.DoctorId,
		PatientID:          req.PatientId,
		ConsultationType:   int(req.ConsultationType),
		SymptomDescription: req.SymptomDescription,
		ImageUrls:          model.StringArray(req.ImageUrls),
		Status:             1, // 待支付
		Fee:                fee,
		CreatedAt:          time.Now(),
		UpdatedAt:          time.Now(),
	}

	if err := config.GlobalDB.Create(consultation).Error; err != nil {
		return nil, err
	}

	// 4. 创建订单
	orderNo := model.GenerateOrderNo(2) // 2表示问诊订单
	order := &model.Order{
		OrderNo:   orderNo,
		UserID:    req.UserId,
		OrderType: 2, // 问诊
		Status:    1, // 待支付
		Amount:    fee,
		RelatedID: consultation.ID,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	if err := config.GlobalDB.Create(order).Error; err != nil {
		return nil, err
	}

	// 5. 更新问诊记录的订单ID
	config.GlobalDB.Model(consultation).Update("order_id", order.ID)

	return &patient.CreateConsultationResponse{
		Message:        "问诊创建成功",
		ConsultationId: consultation.ID,
		OrderId:        order.ID,
		OrderNo:        order.OrderNo,
	}, nil
}

// GetConsultationDetail 获取问诊详情
func (s *PatientServiceServer) GetConsultationDetail(ctx context.Context, req *patient.GetConsultationDetailRequest) (*patient.ConsultationDetailResponse, error) {
	var consultation model.Consultation
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.ConsultationId, req.UserId).First(&consultation).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.ConsultationDetailResponse{Message: "问诊记录不存在"}, nil
		}
		return nil, err
	}

	// 获取患者信息
	var patientInfo model.Patient
	config.GlobalDB.Where("id = ?", consultation.PatientID).First(&patientInfo)

	// TODO: 调用 doctor-srv 获取医生信息
	doctorName := fmt.Sprintf("医生%d", consultation.DoctorID)

	return &patient.ConsultationDetailResponse{
		Message: "获取成功",
		Consultation: &patient.ConsultationInfo{
			Id:                 consultation.ID,
			UserId:             consultation.UserID,
			DoctorId:           consultation.DoctorID,
			DoctorName:         doctorName,
			PatientId:          consultation.PatientID,
			PatientName:        patientInfo.Name,
			ConsultationType:   int32(consultation.ConsultationType),
			SymptomDescription: consultation.SymptomDescription,
			ImageUrls:          consultation.ImageUrls,
			Status:             int32(consultation.Status),
			Fee:                consultation.Fee,
			CreatedAt:          consultation.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:          consultation.UpdatedAt.Format("2006-01-02 15:04:05"),
		},
	}, nil
}

// GetConsultationList 获取问诊列表
func (s *PatientServiceServer) GetConsultationList(ctx context.Context, req *patient.GetConsultationListRequest) (*patient.ConsultationListResponse, error) {
	var consultations []model.Consultation
	query := config.GlobalDB.Where("user_id = ?", req.UserId)

	// 如果指定状态，添加条件
	if req.Status > 0 {
		query = query.Where("status = ?", req.Status)
	}

	// 分页
	page := req.Page
	pageSize := req.PageSize
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	// 查询总数
	var total int64
	query.Model(&model.Consultation{}).Count(&total)

	// 查询列表
	err := query.Order("id DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&consultations).Error
	if err != nil {
		return nil, err
	}

	var result []*patient.ConsultationInfo
	for _, cons := range consultations {
		// 获取患者信息
		var patientInfo model.Patient
		config.GlobalDB.Where("id = ?", cons.PatientID).First(&patientInfo)

		result = append(result, &patient.ConsultationInfo{
			Id:                 cons.ID,
			UserId:             cons.UserID,
			DoctorId:           cons.DoctorID,
			DoctorName:         fmt.Sprintf("医生%d", cons.DoctorID),
			PatientId:          cons.PatientID,
			PatientName:        patientInfo.Name,
			ConsultationType:   int32(cons.ConsultationType),
			SymptomDescription: cons.SymptomDescription,
			ImageUrls:          cons.ImageUrls,
			Status:             int32(cons.Status),
			Fee:                cons.Fee,
			CreatedAt:          cons.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:          cons.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return &patient.ConsultationListResponse{
		Message:       "获取成功",
		Consultations: result,
		Total:         int32(total),
	}, nil
}

// UpdateConsultationStatus 更新问诊状态
func (s *PatientServiceServer) UpdateConsultationStatus(ctx context.Context, req *patient.UpdateConsultationStatusRequest) (*patient.BaseResponse, error) {
	// 查询问诊记录
	var consultation model.Consultation
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.ConsultationId, req.UserId).First(&consultation).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.BaseResponse{Message: "问诊记录不存在"}, nil
		}
		return nil, err
	}

	// 更新状态
	if err := config.GlobalDB.Model(&consultation).Updates(map[string]interface{}{
		"status":     req.Status,
		"updated_at": time.Now(),
	}).Error; err != nil {
		return nil, err
	}

	return &patient.BaseResponse{Message: "更新成功"}, nil
}

// SubmitConsultationDescription 提交病情描述
func (s *PatientServiceServer) SubmitConsultationDescription(ctx context.Context, req *patient.SubmitConsultationDescriptionRequest) (*patient.BaseResponse, error) {
	// 查询问诊记录
	var consultation model.Consultation
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.ConsultationId, req.UserId).First(&consultation).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.BaseResponse{Message: "问诊记录不存在"}, nil
		}
		return nil, err
	}

	// 更新病情描述
	updates := map[string]interface{}{
		"updated_at": time.Now(),
	}
	if req.Description != "" {
		updates["symptom_description"] = req.Description
	}
	if len(req.ImageUrls) > 0 {
		updates["image_urls"] = model.StringArray(req.ImageUrls)
	}

	if err := config.GlobalDB.Model(&consultation).Updates(updates).Error; err != nil {
		return nil, err
	}

	return &patient.BaseResponse{Message: "提交成功"}, nil
}
